<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">

    <title>Utbudstjänst - Utbud</title>

    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="../css/font-awesome.css">
    <link rel="stylesheet" href="../css/bootstrap.css">
    <link rel="stylesheet" href="../css/prism.css">
    <link rel="stylesheet" href="../css/chosen.min.css">
    <link rel="stylesheet" href="../css/bootstrap-responsive.css">
    <link rel="stylesheet" href="../css/datepicker.css">
    <link rel="stylesheet" href="../css/tablesorter.css">
    <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.21.custom.css">
    <link rel="stylesheet" href="../css/application-ocean-breeze.css">
    <link rel="stylesheet" href="../css/msgGrowl.css" type="text/css" charset="utf-8" />
    <link rel="stylesheet" href="../css/jquery.msgbox.css">
    <link rel="stylesheet" href="../css/jquery.dataTables.css">
    <script src="../js/lib/modernizr-2.5.3.min.js"></script>
</head>

<body>
<script id="detailTemplate" type="text/html">
    <div id="edit-utbudspunkt" class="row-fluid">
        <h2 class="closeable unmodified"><i class="icon-check-minus"></i> <span id="edit-title">Ny utbudspunkt</span></h2>
        <div class="row-fluid unmodified">
            <div class="alert">
                <strong>Du har osparade ändringar!</strong> För att stänga raden måste du <a class="action-save">spara</a> eller <a class="action-cancel">avbryta</a>.
            </div>
        </div>

        <div class="row-fluid">
            <div class="span4">
                <label for="hsaID">HSA-ID</label>
                <input id="hsaId" type="text" class="disable-on-edit" placeholder="Ange HSA-ID för utbudspunkt">
            </div>

            <div class="span8">
                <p id="unitDescription"></p>
            </div>
        </div>

        <!-- Tabbed panes for adding services and users to an unit -->
        <div class="tabbable">
            <ul class="nav nav-tabs">
                <li id="tabb1" class="active">
                    <a href="#tab1" data-toggle="tab"> Tjänster </a>
                </li>
                <li id="tabb2">
                    <a href="#tab2" data-toggle="tab"> Användare </a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="tab1">
                    <table id="productTable" class="table table-hover table-striped">
                        <thead>
                        <th width="10%">Produkt-ID</th>
                        <th width="35%">Tjänst</th>
                        <th width="50%">Beskrivning</th>
                        <th width="5%"></th>
                        </thead>
                    </table>
                    <div class="control-group padded">
                        <select id="productList"></select>
                        <button id="addProduct" class="btn pull-right listen-click" disabled="true"><i class="icon-plus"></i> Lägg till tjänst</button>
                    </div>
                </div> <!-- /#tab1 -->
                <div class="tab-pane" id="tab2">
                    <table id="userTable" class="table table-hover table-striped">
                        <thead>
                        <th width="25%">Namn</th>
                        <th width="25%">Användar-ID</th>
                        <th width="25%">E-post</th>
                        <th width="23%">Behörighet</th>
                        <th width="2%"></th>
                        </thead>
                    </table>
                    <div class="control-group padded">
                        <select id="userList"></select>
                        <button id="addUser" class="btn pull-right listen-click" disabled="true"><i class="icon-plus"></i> Lägg till användare</button>
                    </div>

                </div> <!-- /#tab2 -->
            </div> <!-- /.tab-content -->
        </div> <!-- .tabbable -->

        <!-- Actions Save & Cancel -->
        <div class="row-fluid actions-item">
            <div class="span12 unmodified">
                <div class="pull-right">
                    <a class="btn action-cancel"><i class="icon-remove"></i> Avbryt</a>
                    <a class="btn btn-primary action-save" disabled="disabled"><i class="icon-thumbs-up"></i> Spara</a>
                </div>
            </div>
        </div>
    </div>
</script>

<!-- Main list view -->
<div id="wrapper">
    <div id="headerPlaceholder"></div>

    <div id="content">
        <div class="container">
            <div id="createPlaceholder" class="info_row hidden"></div>

            <div class="row">
                <!-- Main Content -->
                <div class="span12" id="top">

                    <div id="add-utbud" class="hero-unit hidden">
                        <legend id="titleUtbud"><i class="icon-medkit"></i> Ny utbudspunkt</legend>
                        <div class="row-fluid">
                            <div class="span8">
                                <div class="control-group" id="offer-hsa">
                                    <label>HSA-ID</label>
                                    <div class="controls">
                                        <input id="hsaOffer" class="input-xxlarge" type="text" />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="pull-right">
                            <a id ="bOfferCancel"><i class="icon-remove" style="position:relative;top:5px;"></i> Avbryt</a>&nbsp;&nbsp;&nbsp;<button id="bSaveOffer" class="btn btn-primary"><i class="icon-thumbs-up"></i> Spara</button>
                        </div>
                    </div>

                    <table id="offerTable" class="table table-hover table-striped">
                        <thead>
                        <tr>
                            <th width="40%" class="sortable">Vårdgivare</th>
                            <th width="30%" class="sortable">HSA-ID</th>
                            <th width="30%" class="sortable">Status</th>
                        </tr>
                        </thead>
                        <tbody id="tbodyUnits">
                        </tbody>
                    </table>
                </div>
            </div><!--/span-->
        </div><!--/row-->
    </div>
</div>

<script src="../js/lib/jquery-1.7.2.min.js"></script>
<script src="../js/lib/jquery-ui-1.8.21.custom.min.js"></script>
<script src="../js/lib/jquery.ui.touch-punch.min.js"></script>
<script src="../js/lib/bootstrap.min.js"></script>
<script src="../js/lib/moment.min.js"></script>
<script src="../js/lib/jquery.tablesorter.min.js"></script>
<script src="../js/lib/jquery.dataTables.js"></script>
<script src="../js/lib/jquery.validate.js"></script>
<script src="../js/lib/chosen.jquery.min.js"></script>
<script src="../js/lib/msgGrowl.min.js"></script>
<script src="../js/lib/jquery.cookie.js"></script>
<script src="../js/lib/jquery-handlebars-1.1.4.min.js"></script>
<script src="../js/md.js"></script>
<script src="../js/common.js"></script>
<script>
            var offerGet = config.guiURL + '/view/offer';
            var offerPut = config.offerURL;
            var offerPost = config.offerURL;

            commonInit({
                tabOffer: true,
                viewDataUrl: offerGet,
                mastheadTitle: 'Utbud',
                mastheadSubtitle: 'Administrera och lägg till utbud',
                mastheadContent: '<a id="bAddOffer" class="pull-right btn" onclick="$(\'#offerTable\').MasterDetail(\'toggleCreateDetail\');"><i class="icon-plus"></i> Lägg till utbudspunkt</a>'
            });

            $("#offerTable").MasterDetail({
                masterData: viewData.offer,
                masterTableId: 'offerTable',
                masterColumns: [
                    {
                        mData: 'relativeDistinguishedName',
                        mRender: MasterDetail.renderString
                    }, {
                        mData: 'unitId',
                        mRender: MasterDetail.renderString
                    }, {
                        mData: 'status',
                        sDefaultContent: 'ACTIVE',
                        mRender: MasterDetail.renderActiveNoActive
                    }],
                initDetail: initDetail,
                createDetail: createDetail,
                updateDetail: updateDetail,
                validateDetail: validateDetail
            });

            // Init detailed view with subDetail for product and users
            function initDetail(container, data) {
                setUniqueTabId(container);
                
                var itemTitle = null;
                if (data) {
                    itemTitle = data.relativeDistinguishedName;
                }
                if (itemTitle === null) {
                    itemTitle = 'Utbudspunkt utan namn';
                }
                var productReferences = [];
                if (data) {
                    $('#hsaId', container).val(data.unitId);
                    $('#edit-title', container).text(itemTitle);
                    $('#unitDescription', container).val(data.displayName);
                    $('.disable-on-edit', container).attr('disabled', 'disabled');
                    productReferences = data.productReferences;
                } else {
                    // Hide 
                    $('#unitDescription').addClass('hidden');
                    $('.disable-on-new').attr('disabled', 'disabled');
                    productReferences = [];
                }
                var productTable = setUniqueId($('#productTable', container)).dataTable({
                    aoColumns: [
                        {mData: 'product.name',
                            mRender: MasterDetail.renderString
                        },
                        {mData: 'product.displayName',
                            mRender: MasterDetail.renderString
                        },
                        {mData: 'product.description',
                            mRender: MasterDetail.renderString
                        },
                        {sDefaultContent: '<a class="delete-unit"><i class="icon-trash listen-click"></i></a>',
                            bSortable: false,
                            bSearchable: false
                        }
                    ],
                    bDeferRender: true,
                    bFilter: false,
                    bDestroy: true,
                    bSortCellsTop: true,
                    bPaginate: false,
                    bInfo: false,
                    aaData: productReferences,
                    fnCreatedRow: function(row, data, dataIndex) {
                        $('.delete-unit', row).click(function() {
                            productTable.fnDeleteRow(row);
                        });
                    }
                });

                // Initialize userlist tab
                var userList = [];
                if (data) {
                    userList = getUserList(data.unitId);
                }
                var userTable = setUniqueId($('#userTable', container)).dataTable({
                    aoColumns: [
                        {mData: 'realname',
                            mRender: MasterDetail.renderString
                        },
                        {mData: 'hsaId',
                            mRender: MasterDetail.renderString
                        },
                        {mData: 'email',
                            mRender: MasterDetail.renderString
                        },
                        {mData: 'role',
                            mRender: renderRole
                        },
                        {sDefaultContent: '<a class="delete-unit"><i class="icon-trash listen-click"></i></a>',
                            bSortable: false,
                            bSearchable: false
                        }
                    ],
                    bDeferRender: true,
                    bFilter: false,
                    bDestroy: true,
                    bSortCellsTop: true,
                    bPaginate: false,
                    bInfo: false,
                    aaData: userList,
                    fnCreatedRow: function(row, data, dataIndex) {
                        $('.delete-unit', row).click(function() {
                            userTable.fnDeleteRow(row);
                        });
                    }
                });
                // Populate product list for the detail view, and bind callback
                var productSelect = $('#productList', container);
                productSelect.append('<option></option>');
                $.each(viewData.product, function(key, val) {
                    if (val.status === "ACTIVE") {
                        productSelect.append('<option value="' + val.name + '">' + val.displayName + '</option>');
                    }
                });
                productSelect.chosen({
                    placeholder_text_single: 'Välj tjänst...',
                    disable_search_treshold: 10,
                    width: '480px'
                });
                $('#addProduct', container).click(function() {
                    addProductToTableView(productTable, productSelect);
                    $('#addProduct', container).prop('disabled', true);
                });
                productSelect.on('change', function(evt, params) {
                    $('#addProduct', container).prop('disabled', false);
                });

                // Populate user list for the detail view, and bind callback
                var userSelect = $('#userList', container);
                userSelect.append('<option></option>');
                $.each(viewData.user, function(key, val) {
                    if (val.status === "ACTIVE") {
                        userSelect.append('<option value="' + val.hsaId + '">' + val.hsaId + '</option>');
                    }
                });
                userSelect.chosen({
                    placeholder_text_single: 'Välj användare...',
                    disable_search_treshold: 10,
                    width: '480px'
                });
                $('#addUser', container).click(function() {
                    addUserToTableView(userTable, userSelect);
                    $('#addUser', container).prop('disabled', true);
                });
                userSelect.on('change', function(evt, params) {
                    $('#addUser', container).prop('disabled', false);
                });
            }

            function createDetail(container, data) {
                var hsaId = $('#hsaId', container).val();
                var productList = $("table[id^='productTable']", container).dataTable().fnGetData();
                var userTable = $("table[id^='userTable']", container).dataTable();
                var queryString = buildProductReferenceQueryString(productList);
                $('#edit-product', container).validate({
                    rules: {
                        productDisplayName: "required",
                        productDescription: "required"
                    },
                    messages: {
                        productDisplayName: "Namn måste anges",
                        productDescription: "Beskrivning måste anges"
                    }
                });
                createOffer(hsaId);
                setProductReferences(hsaId, queryString);
                setUserOnCareUnit(hsaId, userTable);
                return getOffer(hsaId);
            }


            // Update details for an offer
            function updateDetail(container) {
                // Update product references
                var hsaId = $('#hsaId', container).val();
                var productList = $("table[id^='productTable']", container).dataTable().fnGetData();
                var userTable = $("table[id^='userTable']", container).dataTable();
                var queryString = buildProductReferenceQueryString(productList);
                setProductReferences(hsaId, queryString);
                setUserOnCareUnit(hsaId, userTable);
                return getOffer(hsaId);
            }

            /**
            * Validates form
            * 
            * @param {type} container
            * @returns {true or false}
            */
            function validateDetail(container) {
                return true;
            }

            /**
             * Support methods
             */

            /**
             * 
             * @param {type} hsaId
             * @returns {unresolved}
             */
            function getOffer(hsaId) {
                var response = null;
                $.ajax({
                    url: config.guiURL + '/view/offer/' + hsaId,
                    type: 'GET',
                    data: null,
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(data) {
                        response = data;
                    }
                });
                return response.offer[0];
            }

            /**
             * Fetch all users.
             * 
             * @param {type} hsaId
             * @returns {data}
             */
            function getUserList(hsaId) {
                var response = null;
                $.ajax({
                    url: config.guiURL + '/users/units/' + hsaId,
                    type: 'GET',
                    data: null,
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(data) {
                        response = data;
                    }
                });
                return response;
            }

            /**
             * Lookup displayName for role
             * @param {type} data
             * @param {type} type
             * @param {type} full
             * @returns {unresolved}
             */
            function renderRole(data, type, full) {
                if (viewData.roles[data] === null) {
                    return MasterDetail.renderString(data, type, full);
                } else {
                    return MasterDetail.renderString(viewData.roles[data], type, full);
                }
            }

            /**
             * 
             * @param {type} hsaId
             * @param {type} userTable
             * @returns {undefined}
             */
            function setUserOnCareUnit(hsaId, userTable) {
                var userList = userTable.fnGetData();
                var userNames = [];
                $.each(userList, function(i) {
                    userNames.push(userList[i].hsaId);
                });
                var request = {
                    unitId: hsaId,
                    hsaId: userNames
                };
                $.ajax({
                    url: config.guiURL + '/users/units/setusers',
                    type: 'PUT',
                    data: JSON.stringify(request),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(msg) {
                        showGrowlMessage('Utbudspunkt uppdaterad.');
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                    }
                });
            }

            /**
             * Creates an offer based on the hsaId
             * 
             * @param {type} hsaId
             * @returns {undefined}
             */
            function createOffer(hsaId) {
                var data = '{"hsaID":"' + hsaId + '"}';
                var response = null;
                $.ajax({
                    url: offerPut + '/units/',
                    type: 'POST',
                    data: data,
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(msg) {
                        showGrowlMessage('Utbudspunkt skapad.');
                        response = data;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                        if (textStatus==='error' && errorThrown==='Unauthorized') {
                            alert("Din användarsession har gått ut, du måste logga in på nytt!")
                            $(location).attr('href','../');
                        }
                    }
                });
                return response;
            }

            // Calls REST-API on offers to set product references for given hsaId
            function setProductReferences(hsaId, queryString) {
                if (hsaId === null || hsaId === '') {
                    showErrorGrowlMessage("Felaktigs HSA-ID");
                    return;
                }
                $.ajax({
                    url: offerPut + '/units/' + hsaId + '/products/?' + queryString,
                    type: 'POST',
                    contentType: 'application/json; charset=UTF-8',
                    async: false,
                    success: function(msg) {
//                        showGrowlMessage('Utbudspunkt uppdaterad.');
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                    }
                });
            }

            // Build query string for updating product references
            function buildProductReferenceQueryString(productReferences) {
                var queryString = "product=";
                $.each(productReferences, function(i) {
                    queryString += productReferences[i].product.name + ',';
                });
                queryString = queryString.slice(0, -1);
                return queryString;
            }

            // Update user table view with selected user
            function addUserToTableView(table, select) {
                var id = select.val();
                // Avoid duplicates
                var existing = $.grep(table.fnGetData(), function(e) {
                    return e.id === id;
                });
                if (existing.length === 0) {
                    table.fnAddData({
                        realname: viewData.user[id].realname,
                        hsaId: viewData.user[id].hsaId,
                        email: viewData.user[id].email,
                        role: viewData.user[id].role
                    });
                }
                // Reset selection
                select.chosen().val('');
                select.trigger('chosen:updated');
            }

            // Update product table view with selected product
            function addProductToTableView(table, select) {
                var id = select.val();
                // Avoid duplicates
                var existing = $.grep(table.fnGetData(), function(e) {
                    return e.product.name === id;
                });
                if (existing.length === 0) {
                    table.fnAddData({
                        product: {
                            name: id,
                            displayName: viewData.product[id].displayName,
                            description: viewData.product[id].description
                        }
                    });
                }
                // Reset selection
                select.chosen().val('');
                select.trigger('chosen:updated');
            }
        </script>
</body>
</html>
